"""Multi-texture support for pyglet vertex lists

This is a bit of a hack, and may break with pyglet versions other than 1.1.1
"""

import re
from pyglet.graphics import vertexattribute
import pyglet
from pyglet.gl import *


class MultiTexCoorAttribute(vertexattribute.TexCoordAttribute):
	
	plural = 'multitex_coords'
	texture_unit = 0
	
	def set_pointer(self, pointer):
		glClientActiveTexture(GL_TEXTURE0 + self.texture_unit)
		glEnable(GL_TEXTURE_2D)
		vertexattribute.TexCoordAttribute.set_pointer(self, pointer)

def enable(vertex_list):
	"""Enable multi-texturing for this vertex list where multiple 
	texture coordinate attributes are specified. Texture units
	are assigned in order of the tex coord attributes, with the
	first having texture unit 0, the second unit 1, etc.
	"""
	next_unit = 0
	for buffer, attributes in vertex_list.domain.buffer_attributes:
		for attribute in attributes:
			if isinstance(attribute, MultiTexCoorAttribute):
				attribute.texture_unit = next_unit
				next_unit += 1

# Insinuate our own class in place of the std pyglet TexCoordAttribute class
vertexattribute._attribute_classes['t'] = MultiTexCoorAttribute

if __name__ == '__main__':
	win = pyglet.window.Window()
	glEnable(GL_BLEND)
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
	splat = pyglet.image.load('texture/splat.png').texture
	dirt = pyglet.image.load('texture/bare-ground.png').texture

	vl = pyglet.graphics.vertex_list(4,
		('v2f', (100, 100, 200, 100, 200, 200, 100, 200)),
		('t2f', (0, 0, 1, 0, 1, 1, 0, 1)),
		('t2f', (0, 0, 0.25, 0, 0.25, 0.25, 0, 0.25)),
		)
	enable(vl)

	@win.event
	def on_draw():
		win.clear()
		glActiveTexture(GL_TEXTURE0)
		glClientActiveTexture(GL_TEXTURE0)
		glEnable(splat.target)
		glBindTexture(splat.target, splat.id)

		glActiveTexture(GL_TEXTURE1)
		glClientActiveTexture(GL_TEXTURE1)
		glEnable(dirt.target)
		glBindTexture(dirt.target, dirt.id)

		vl.draw(GL_QUADS)
	pyglet.app.run()
